package diplom.shop.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.sun.org.apache.regexp.internal.recompile;

import diplom.shop.domain.Category;
import diplom.shop.domain.Motherboard;
import diplom.shop.domain.Mouse;
import diplom.shop.domain.Processor;

public class MouseDAO {
	private Session session = null;
	private Transaction transaction = null;

	public MouseDAO() {
		super();
	}

	private Session connect() {
		session = HibernateUtil.getSessionFactory().openSession();
		transaction = session.beginTransaction();
		return session;
	}

	private void close() {
		this.transaction.commit();
		this.session.close();
	}
	
	//Category
	
	public List<Category> getCategoryList() {
		List<Category> categoryList = connect().createCriteria(diplom.shop.domain.Category.class).list();
		close();
		return categoryList;
	}
	public Category getCategoryById(Long id){
		Category category = (Category) connect().load(Category.class, id);
		close();
		return category;
	}
	////////////
// mouse
	public void addMouse(Mouse mouse) {
		connect().saveOrUpdate(mouse);
		close();
	}

	public Mouse getMouseByName(Mouse mouse) {

		// List<Mouse> mouses =
		// connect().createQuery("from diplom.shop.domain.Device device where device.devicename like '"+mouse.getDeviceName()+"'").list();
		List<Mouse> mouses = connect()
				.createCriteria(diplom.shop.domain.Device.class)
				.add(Restrictions.like("deviceName", mouse.getDeviceName()))
				.list();

		if (mouses.size() != 0) {
			mouse = mouses.get(0);
		} else {
			mouse = null;
		}
	
		close();
		return mouse;
	}

	public void deleteMouse(Mouse mouse) {
		mouse = getMouseByName(mouse);
		if (mouse!=null) {
			connect().delete(mouse);
			close();
		}
	}
	///processor
	public void addProcessor(Processor processor) {
		connect().saveOrUpdate(processor);
		close();
	}
///Motherboard
	public void addMotherboard(Motherboard mothrboard) {
		connect().saveOrUpdate(mothrboard);
		close();
	}
///////////////
	
	public Mouse getProcessorByName(Mouse mouse) {

		// List<Mouse> mouses =
		// connect().createQuery("from diplom.shop.domain.Device device where device.devicename like '"+mouse.getDeviceName()+"'").list();
		List<Mouse> mouses = connect()
				.createCriteria(diplom.shop.domain.Device.class)
				.add(Restrictions.like("deviceName", mouse.getDeviceName()))
				.list();
		if (mouses.size() != 0) {
			mouse = mouses.get(0);
		} else {
			mouse = null;
		}
		close();
		return mouse;
	}

	public void deleteProcessor(Mouse mouse) {
		mouse = getMouseByName(mouse);
		if (mouse!=null) {
			connect().delete(mouse);
			close();
		}
	}
	///////////

}
